package org.robot;

import org.game.constant.SessionConstent;
import org.game.netty.oldcoder.other.CheckSumUtil;
import org.game.netty.oldcoder.other.EncryptionAndDecryptionUtil;
import org.game.netty.oldcoder.other.IChannelConstants;
import org.game.netty.oldcoder.other.ProtocolConstants;

import com.sojoys.artifact.factory.message.IMessage;
import com.sojoys.artifact.factory.session.ISession;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.util.Attribute;

/**
 * 明文单协议编码器
 * @author wk.dai
 */
public class EchoEncoder extends MessageToByteEncoder<IMessage> {

	@Override
	protected void encode(ChannelHandlerContext ctx, IMessage msg,ByteBuf out) throws Exception {
		int contentLength = msg.getBodyLength() + ProtocolConstants.DEFAULT_HEADER_SIZE;
		out.writeShort(ProtocolConstants.FLAG);
		out.writeInt(contentLength);
		int backWriterIndex = out.writerIndex();
		out.writeShort(0);
		out.writeShort(msg.getCommandId());
		if(msg.getBody()!=null)
			out.writeBytes(msg.getBody());

		int lastWriterIndex = out.writerIndex();
		int checkSum = CheckSumUtil.calculate(out.nioBuffer(),ProtocolConstants.CHECKSUM_SKIP_SIZE_FOR_CONTENT, contentLength - ProtocolConstants.CHECKSUM_SKIP_SIZE_FOR_CONTENT);
		out.writerIndex(backWriterIndex);
		out.writeShort(checkSum);
		out.writerIndex(lastWriterIndex);
		
		
		Attribute<ISession> attach = ctx.channel().attr(IChannelConstants.SESSION);
		int[] encryptKeys = attach.get().getAttr(SessionConstent.ENCRYPTION_KEYS);
		EncryptionAndDecryptionUtil.encryptCustom(out.nioBuffer(), encryptKeys,out.readableBytes());
	}

}
